package com.iot.controller;

import com.iot.core.PageData;
import com.iot.util.Common;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@CrossOrigin(origins = "*", maxAge = 3600)
public class BaseController {

    @RequestMapping("list")
    public String list(Model model, HttpServletRequest request) throws Exception {
        return Common.BACKGROUND_PATH + findUrl()[0] + "/list";
    }
    @RequestMapping("add")
    public String add(Model model, HttpServletRequest request) throws Exception {
        return Common.BACKGROUND_PATH + findUrl()[0] + "/edit";
    }

    @RequestMapping("edit")
    public String edit(Model model, HttpServletRequest request) throws Exception {
        return Common.BACKGROUND_PATH + findUrl()[0] + "/edit";
    }


    public String[] findUrl() {
        RequestMapping annotation = this.getClass().getAnnotation(RequestMapping.class);
        return annotation.value();
    }


    /**
     * 根据当前Request得到PageData
     *
     * @return the page data
     */
    public PageData getPageData() {
        return new PageData(this.getRequest());
    }

    /**
     * 得到ModelAndView
     *
     * @return the model and view
     */
    public ModelAndView getModelAndView() {
        return new ModelAndView();
    }

    /**
     * 得到request对象
     * @return the request
     */
    public HttpServletRequest getRequest() {
        // 利用spring api获取当前request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }


}
